package com.funtonow.jqdk.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chaychan.viewlib.utils.StringUtils;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.adapter.HomeBannerAdapter;
import com.funtonow.jqdk.adapter.LoanListAdapter;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.BaseFragment;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.base.UrlUtils;
import com.funtonow.jqdk.bean.DkNumBean;
import com.funtonow.jqdk.bean.GameThirdInfoListBean;
import com.funtonow.jqdk.bean.HkInfoBean;
import com.funtonow.jqdk.bean.LoanInfoBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.event.LoanInfoEvent;
import com.funtonow.jqdk.fkcs.ui.DkFailActivity;
import com.funtonow.jqdk.fkcs.ui.DkSuccessActivity;
import com.funtonow.jqdk.ui.ExamineFailActivity;
import com.funtonow.jqdk.ui.ExamineSuccessActivity;
import com.funtonow.jqdk.ui.LoginActivity;
import com.funtonow.jqdk.ui.UserInfoActivity;
import com.funtonow.jqdk.ui.VipActivity;
import com.funtonow.jqdk.utils.AppUtils;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.PhoneUtils;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.StringUtil;
import com.funtonow.jqdk.utils.TimeUtils;
import com.funtonow.jqdk.utils.ToastUtils;
import com.funtonow.jqdk.widget.AutoSwipeRefreshView;
import com.superluo.textbannerlibrary.TextBannerView;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Call;

import static com.funtonow.jqdk.base.Constants.INTO_HOME;
import static com.funtonow.jqdk.base.UrlUtils.DK_ONLINE_NUM;
import static com.funtonow.jqdk.base.UrlUtils.ED_JS;
import static com.funtonow.jqdk.base.UrlUtils.HK_LIST;
import static com.funtonow.jqdk.base.UrlUtils.HOME_LIST;

/**
 * @author Jiajien
 * @date 2019/6/17
 */
public class HomeFragment extends BaseFragment {

    @BindView(R.id.rlv_loan)
    RecyclerView recyclerView;
    @BindView(R.id.rlv_banner)
    RecyclerView rlvBanner;
    @BindView(R.id.tv_banner)
    TextBannerView tvBanner;
    @BindView(R.id.tv_money_banner)
    TextBannerView tvMoneyBanner;
    @BindView(R.id.tv_dk_money)
    TextView tvDkMoney;
    @BindView(R.id.ll_dk_money)
    LinearLayout llDkMoney;
    @BindView(R.id.auto_refresh)
    AutoSwipeRefreshView autoSwipeRefreshView;
    @BindView(R.id.ll_tip)
    LinearLayout llTip;
    @BindView(R.id.ll_money_banner)
    LinearLayout llMonerBanner;

    //  贷款
    @BindView(R.id.ll_dk_fail)
    View llFkFail;
    @BindView(R.id.ll_dk_success)
    View llFkSuccess;
    @BindView(R.id.tv_dk_num)
    TextView tvDkNum;
    @BindView(R.id.tv_dk_info)
    TextView tvDkInfo;


    private LoanListAdapter loanListAdapter;
    private HomeBannerAdapter homeBannerAdapter;
    private List<String> strings = new ArrayList<>();

    private List<GameThirdInfoListBean> gameThirdInfoListBeans = new ArrayList<>();
    private List<GameThirdInfoListBean> bannerInfoList = new ArrayList<>();

    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View getLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, null);
    }

    @Override
    public void onCreateFragment(@Nullable Bundle savedInstanceState) {
        initRecyclerView(recyclerView);
        initRecyclerView(rlvBanner);
        initData();

        autoSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getAppId();
            }
        });
        if (SqjAppliaction.loanInfoBean == null) {
            autoSwipeRefreshView.autoRefresh();
        } else {
            setLoanData(SqjAppliaction.loanInfoBean);
        }
        StatisticsUtils.baoGuang(String.format("%s,%s", Constants.HEZI_ID_20, Constants.HEZI_ID_21));
        StatisticsUtils.eventLog(INTO_HOME, null);
        if (AppUtils.getAppName(getActivity()).equals(getResources().getString(R.string.ssq_app_name))) {
            getMoneyNum();
        } else {
            llFkFail.setVisibility(View.GONE);
            llFkSuccess.setVisibility(View.GONE);
        }
    }


    private void initData() {
        homeBannerAdapter = new HomeBannerAdapter();
        rlvBanner.setAdapter(homeBannerAdapter);
        loanListAdapter = new LoanListAdapter();
        recyclerView.setAdapter(loanListAdapter);
        loanListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (SPUtil.getUserInfo() == null) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else if (SPUtil.getUserInfo() != null && loanListAdapter.getItem(position).getVipfw() == 1
                        && SPUtil.getUserInfo().getHasVip() == 0) {
                    ToastUtils.show("该产品仅限会员申请");
                    startActivity(new Intent(getActivity(), VipActivity.class));
                } else {
                    StatisticsUtils.clickUrl(loanListAdapter.getItem(position));
                    StatisticsUtils.intentWebView(getActivity(),
                            loanListAdapter.getItem(position).getUrl(), loanListAdapter.getItem(position).getName(),
                            loanListAdapter.getItem(position).getChanpinid());
                }
            }
        });

        homeBannerAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                if (SPUtil.getUserInfo() == null) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else if (SPUtil.getUserInfo() != null && homeBannerAdapter.getItem(position).getVipfw() == 1
                        && SPUtil.getUserInfo().getHasVip() == 0) {
                    ToastUtils.show("该产品仅限会员申请");
                    startActivity(new Intent(getActivity(), VipActivity.class));
                } else {
                    SPUtil.put("dkAppId", homeBannerAdapter.getItem(position).getVipfw());
                    LoanInfoBean.InfoBean infoBean = SPUtil.getInfoBean();
                    assert infoBean != null;
                    if (!StringUtil.isEmpty(infoBean.getPingbidiqu()) && Integer.valueOf(infoBean.getPingbidiqu()) > 0) {
                        if (TimeUtils.isShowUserInfo()) {
                            startActivity(new Intent(getActivity(), UserInfoActivity.class));
                        } else {
                            if (Integer.valueOf(infoBean.getAdvideoid()) > 0) {  // 审核失败
                                startActivity(new Intent(getActivity(), ExamineSuccessActivity.class));
                            } else {
                                Intent intent = new Intent(getActivity(), ExamineFailActivity.class);
                                intent.putExtra("isFail", true);
                                startActivity(intent);
                            }
                        }
                    } else {
                        StatisticsUtils.clickUrl(homeBannerAdapter.getItem(position));
                        StatisticsUtils.intentWebView(getActivity(),
                                homeBannerAdapter.getItem(position).getUrl(), homeBannerAdapter.getItem(position).getName(),
                                homeBannerAdapter.getItem(position).getChanpinid());
                    }

                }
            }
        });
    }

    private void initRecyclerView(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void onResume() {
        super.onResume();
        tvBanner.startViewAnimator();
        tvMoneyBanner.startViewAnimator();
    }


    @Override
    public void onStop() {
        super.onStop();
        tvBanner.stopViewAnimator();
        tvMoneyBanner.stopViewAnimator();
    }

    /**
     * 获取数据appId
     */
    private void getAppId() {
        HttpUtil.getInstance().getDataAsynFromNet(UrlUtils.GET_APPID, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString);
                Constants.DATA_APP_ID = JSON.parseObject(jsonString).getString("appId");
                getLoanList();
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    private void getLoanList() {
        final Map<String, String> param = new HashMap<>();
        param.put("appid", Constants.DATA_APP_ID);
        param.put("app", "1");
        HttpUtil.getInstance().postDataAsynToNet(HOME_LIST, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                SqjAppliaction.loanInfoBean = JSON.parseObject(jsonString, LoanInfoBean.class);
                setLoanData(SqjAppliaction.loanInfoBean);
            }

            @Override
            public void failed(Call call, IOException e) {
                ToastUtils.show("请求超时，请检查网络");
                autoSwipeRefreshView.setRefreshing(false);
            }
        });
    }


    private void setLoanData(LoanInfoBean loanInfoBean) {
        SPUtil.put(Constants.CONFIG_INFO, SPUtil.beanToJson(loanInfoBean.getInfo()));
        EventBus.getDefault().post(new LoanInfoEvent(loanInfoBean));
        autoSwipeRefreshView.setRefreshing(false);
        if (bannerInfoList.size() > 0) {
            bannerInfoList.clear();
        }
        if (gameThirdInfoListBeans.size() > 0) {
            gameThirdInfoListBeans.clear();
        }
        if (loanInfoBean.getHeziInfoList() != null) {
            for (LoanInfoBean.HeziInfoListBean heziInfoListBean : loanInfoBean.getHeziInfoList()) {
                if (heziInfoListBean.getType() == 20) {
                    JSONObject jsonObject = JSON.parseObject(loanInfoBean.getCpMap());
                    for (LoanInfoBean.GdlistBean gdlistBean : loanInfoBean.getGdlist()) {
                        if (heziInfoListBean.getGdid().equals(gdlistBean.getGdid())) {
                            GameThirdInfoListBean gameThirdInfoListBean = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                            gameThirdInfoListBean.setVipfw(gdlistBean.getVipfw());
                            gameThirdInfoListBean.setUrl(gdlistBean.getUrl());
                            gameThirdInfoListBean.setHeziId(heziInfoListBean.getType());
                            gameThirdInfoListBean.setIndex(heziInfoListBean.getInde());
                            gameThirdInfoListBean.setGdId(gdlistBean.getGdid());
                            bannerInfoList.add(gameThirdInfoListBean);
                        }
                    }
                } else if (heziInfoListBean.getType() == 21) {
                    JSONObject jsonObject = JSON.parseObject(loanInfoBean.getCpMap());
                    for (LoanInfoBean.GdlistBean gdlistBean : loanInfoBean.getGdlist()) {
                        if (heziInfoListBean.getGdid().equals(gdlistBean.getGdid())) {
                            GameThirdInfoListBean gameThirdInfoListBean = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                            gameThirdInfoListBean.setVipfw(gdlistBean.getVipfw());
                            gameThirdInfoListBean.setUrl(gdlistBean.getUrl());
                            gameThirdInfoListBean.setHeziId(heziInfoListBean.getType());
                            gameThirdInfoListBean.setIndex(heziInfoListBean.getInde());
                            gameThirdInfoListBean.setGdId(gdlistBean.getGdid());
                            gameThirdInfoListBeans.add(gameThirdInfoListBean);
                            String s = PhoneUtils.getTelephone() + "在" + gameThirdInfoListBean.getName() +
                                    "成功下款" + gameThirdInfoListBean.getEdumax() + "元";
                            strings.add(s);
                        }
                    }
                }
                homeBannerAdapter.setNewData(bannerInfoList);
                tvMoneyBanner.setDatas(strings);
                loanListAdapter.setNewData(gameThirdInfoListBeans);
                llTip.setVisibility(View.VISIBLE);
                llMonerBanner.setVisibility(View.VISIBLE);
            }
        }
        getDkNum();
    }

    /**
     * 累计放款
     */
    private void getDkNum() {
        Map<String, String> param = new HashMap<>();
        HttpUtil.getInstance().postDataAsynToNet(DK_ONLINE_NUM, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) {
                JSONObject jsonObject = JSON.parseObject(jsonString);
                tvBanner.setDatas(Arrays.asList(jsonObject.getJSONObject("data").getJSONObject("msg").getString("T")
                        .split("\n")));
                llDkMoney.setVisibility(View.VISIBLE);
                BigDecimal money = new BigDecimal(jsonObject.getJSONObject("data").getLong("leiji"));
                NumberFormat format = new DecimalFormat("###,###");
                tvDkMoney.setText(String.format("%s元", format.format(money)));

            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    /**
     * 得到可贷款金额
     */
    private void getMoneyNum() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        HttpUtil.getInstance().postDataAsynToNet(ED_JS, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString + " *********  ");
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum > -1) {
                    DkNumBean dkNumBean = JSON.parseObject(baseBean.data, DkNumBean.class);
                    if (dkNumBean.getKtxed() > 0) {
                        llFkFail.setVisibility(View.GONE);
                        llFkSuccess.setVisibility(View.VISIBLE);
                        getHkList(dkNumBean.getKtxed());
                    } else {
                        llFkSuccess.setVisibility(View.GONE);
                        llFkFail.setVisibility(View.VISIBLE);
                    }

                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    private void getHkList(final int num) {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        HttpUtil.getInstance().postDataAsynToNet(HK_LIST, param, new HttpUtil.MyNetCall() {

            @Override
            public void success(Call call, String jsonString) throws IOException {
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum >= 0) {
                    HkInfoBean hkInfoBean = JSON.parseObject(baseBean.data, HkInfoBean.class);
                    if (hkInfoBean.getList().size() > 0) {
                        tvDkNum.setText(String.valueOf(num));
                        tvDkInfo.setText(String.format(Locale.getDefault(), "近期待还：%s，应还%d元",
                                TimeUtils.dateToString(Long.valueOf(hkInfoBean.getList().get(0).getTime())),
                                Integer.valueOf(hkInfoBean.getList().get(0).getHuankuane())
                                        + Integer.valueOf(hkInfoBean.getList().get(0).getXifei())));
                    }
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

}
